package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.SetMeal;
import com.itheima.service.SetMealService;
import com.itheima.utils.QiNiuUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.itheima.constant.MessageConstant.*;

@Service(version = "1.0", interfaceClass = SetMealService.class)
@Transactional()
public class SetMealServiceImpl implements SetMealService {
    @Resource
    SetMealMapper setMealMapper;
    @Resource
    CheckGroupMapper checkGroupMapper;
    @Resource
    CheckItemMapper checkItemMapper;
    @Resource
    private FreeMarkerConfigurer freemarkerConfig;
    @Value("${out_put_path}")
    private String mobilePath;

    @Override
    public Result findPage(QueryPageBean queryPageBean) {
        try {
            PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
            Page<SetMeal> setMealPage = setMealMapper.findByCondition(queryPageBean.getQueryString());
            PageResult pageResult = new PageResult();
            pageResult.setTotal(setMealPage.getTotal());
            pageResult.setRows(setMealPage.getResult());
            return Result.success(QUERY_SETMEALLIST_SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_SETMEALLIST_FAIL);
    }

    @Override
    public Result save(SetMeal setMeal) {
        try {
            setMealMapper.save(setMeal);
            saveSetMealAndGroup(setMeal, setMeal.getId());
            return Result.success(ADD_SETMEAL_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(ADD_SETMEAL_FAIL);
    }


    private void saveSetMealAndGroup(SetMeal setMeal, Integer setMealId) {
        List<Integer> checkGroupIds = setMeal.getCheckGroupIds();
        for (Integer checkGroupId : checkGroupIds) {
            setMealMapper.saveSetMealAndGroup(setMealId, checkGroupId);
        }
    }

    @Override
    public Result findById(Integer setMealId) {
        try {
            List<CheckGroup> checkGroupList = checkGroupMapper.findAll();
            List<Integer> checkGroupIds = setMealMapper.findGroupIdBySetMealId(setMealId);
            SetMeal setMeal = setMealMapper.findById(setMealId);

            HashMap<String, Object> map = new HashMap<>();
            String imageUrl = QiNiuUtil.prefixUrl + setMeal.getImg();
            map.put("checkGroupList", checkGroupList);
            map.put("checkGroupIds", checkGroupIds);
            map.put("setMeal", setMeal);
            map.put("imageUrl", imageUrl);

            return Result.success(QUERY_CHECKGROUP_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_CHECKGROUP_FAIL);
    }

    @Override
    public Result delete(Integer setMealId) {
        long count = setMealMapper.count(setMealId);
        if (count > 0) {
            return Result.fail(DELETE_SETMEAL_FAIL);
        }
        setMealMapper.delete(setMealId);
        return Result.success(DELETE_SETMEAL_SUCCESS, null);
    }

    @Override
    public Result update(SetMeal setMeal) {
        try {
            setMealMapper.update(setMeal);
            Integer setMealId = setMeal.getId();
            setMealMapper.deleteSetMealAndGroupBySetMealId(setMealId);
            saveSetMealAndGroup(setMeal, setMealId);
            return Result.success(EDIT_SETMEAL_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(EDIT_SETMEAL_FAIL);
    }

    @Override
    public Result findAll() {
        try {
            List<SetMeal> setMealList = setMealMapper.findAll();

            List<SetMeal> collect = updateImgPath(setMealList);

            return Result.success(GET_SETMEAL_LIST_SUCCESS, collect);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(500, GET_SETMEAL_LIST_FAIL);
    }

    @Override
    public Result findSetMealById(Integer setMealId) {
        try {
            SetMeal setMeal = getSetMealAll(setMealId);
            return Result.success(QUERY_SETMEAL_SUCCESS, setMeal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(500, QUERY_SETMEAL_FAIL);
    }

    /**
     * 根据套餐id查询套餐的所有信息
     * @param setMealId 套餐id
     * @return 套餐带检查组和检查项
     */
    private SetMeal getSetMealAll(Integer setMealId) {
        //查询套餐基本信息
        SetMeal setMeal = setMealMapper.findById(setMealId);
        //设置图片路径
        setMeal.setImg(QiNiuUtil.prefixUrl + setMeal.getImg());
        //根据套餐id查询检查组信息
        List<CheckGroup> checkGroupList = checkGroupMapper.findGroupBySetMealId(setMealId);
        ///设置给套餐
        setMeal.setCheckGroups(checkGroupList);
        //遍历检查组
        for (CheckGroup checkGroup : checkGroupList) {
            //获取检查组id
            Integer checkGroupId = checkGroup.getId();
            //根据检查组id获取检查项信息
            List<CheckItem> checkItemList = checkItemMapper.findItemByGroupId(checkGroupId);
            //设置给检查项
            checkGroup.setCheckItems(checkItemList);
        }
        return setMeal;
    }

    @Override
    public Result gen() {
        try {
            //5.创建数据模型
            List<SetMeal> setMealList = setMealMapper.findAll();
            //通过流修改套餐的图片路径
            List<SetMeal> collect = updateImgPath(setMealList);

            Map<String, Object> map = new HashMap<>();
            map.put("setMealList", collect);
            //生成模板
            genTemplate("setmeal.ftl",map,"setmeal_mobile.html");

            //套餐详情
            for (SetMeal sm : setMealList) {
                //通过这个套餐id获取到带有检查组和检查项的套餐
                SetMeal setMeal = this.getSetMealAll(sm.getId());
                Map<String, Object> setMealMap = new HashMap<>();
                setMealMap.put("setmeal", setMeal);
                genTemplate("setmeal_detail.ftl",setMealMap,"setmeal_"+sm.getId()+".html");
            }
            return Result.success(QUERY_SETMEALLIST_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_SETMEALLIST_FAIL);
    }

    private List<SetMeal> updateImgPath(List<SetMeal> setMealList) {
        return setMealList.stream().map(setMeal -> {
            setMeal.setImg(QiNiuUtil.prefixUrl + setMeal.getImg());
            return setMeal;
        }).collect(Collectors.toList());
    }

    public void genTemplate(String templateName, Object dataModel, String target) throws Exception {
        Configuration configuration = freemarkerConfig.getConfiguration();
        //4.加载模板
        Template template = configuration.getTemplate(templateName);

        Writer writer = new FileWriter(new File(mobilePath + target));
        //7.输出
        template.process(dataModel, writer);

    }
}
